package com.example.myapplication.ui.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myapplication.network.api.Product
import com.example.myapplication.network.api.ProductApiService
import com.example.myapplication.network.core.NetworkResult
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class ProductViewModel : ViewModel(){
    //对那私有，可以修改数据
    private val _producsState = MutableStateFlow<NetworkResult<List<Product>>>(NetworkResult.Loading())

    //不可变对象（给UI用的）
    val producsState = _producsState.asStateFlow()

    init {
        getProducts()
    }


    //定义数据请求的方法
    fun getProducts(){
        viewModelScope.launch {
            _producsState.value = NetworkResult.Loading()
            try {
                val products: List<Product> = ProductApiService.getInstance().getProducts()
                println("商品数据："+products.toString())
                _producsState.value = NetworkResult.Success(products)

            }catch (e: Exception){
                _producsState.value = NetworkResult.Error("请求数据失败")
            }
        }
    }
}